package com.timecookfish.mybatisplusdemo.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.timecookfish.mybatisplusdemo.dao.UserMapper;
import com.timecookfish.mybatisplusdemo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.Executor;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserBizServiceImpl userBizService;

    @Transactional
    @Override
    public void addTxMethod() {
        addUser();

        exceptionMethod();

//        int i = 1 / 0;
    }


    @Transactional
    public void addUser() {
        User user = new User();
        user.setId(123132L);
        user.setName("jack112");

        userMapper.insert(user);
    }

    @Transactional
    public void exceptionMethod() {
//        int i = 1 / 0;
        throw new NullPointerException("出错了");
    }


    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void exceptionMethod_requireNew() {
        throw new NullPointerException("出错了。。requireNew");
    }


    /**
     * 外部事务，其中有个内部异常事务
     */
    @Transactional
    @Override
    public void txMethod01(User user) {
        userMapper.insert(user);
        exceptionMethod();
    }

    /**
     * try-required
     * @param user
     */
    @Transactional
    @Override
    public void txMethod02(User user) {

        userMapper.insert(user);
        try {
//            exceptionMethod();
            userBizService.exceptionMethod();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    @Override
    public void txProMandatory() {
        userBizService.txPropagationMandatory();
    }
}
